package com.framework.modules.job.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.common.config.SystemConfigName;
import com.framework.common.model.config.ConfigOperationIncomeRatio;
import com.framework.common.model.config.ConfigPaymentRateMoney2Coin;
import com.framework.common.utils.DateUtils;
import com.framework.common.utils.QuickHelper;
import com.framework.modules.base.entity.SetteleLiveRewardsEntity;
import com.framework.modules.base.entity.UserIncomeHistoryEntity;
import com.framework.modules.base.service.UserIncomeHistoryService;
import com.framework.modules.finance.entity.PlatformIncomeDetailEntity;
import com.framework.modules.finance.entity.PlatformIncomeEntity;
import com.framework.modules.finance.service.PlatformIncomeDetailService;
import com.framework.modules.finance.service.PlatformIncomeService;
import com.framework.modules.guild.entity.GuildIncomeHistoryEntity;
import com.framework.modules.guild.service.GuildIncomeHistoryService;
import com.framework.modules.live.service.LiveRewardsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component("dailySettleAllAccountTask")
public class DailySettleAllAccountTask {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LiveRewardsService liveRewardsService;

    @Autowired
    private UserIncomeHistoryService userIncomeHistoryService;

    @Autowired
    private GuildIncomeHistoryService guildIncomeHistoryService;

    @Autowired
    private PlatformIncomeDetailService platformIncomeDetailService;

    @Autowired
    private PlatformIncomeService platformIncomeService;


    public void run(String params) {
        logger.info("执行直播结算任务开始，当前任务参数为：%s" + params);
        //1.查出无工会主播与平台的分成比例，此为全局参数
        ConfigOperationIncomeRatio configOperationIncomeRatio = QuickHelper.getConfigValue(SystemConfigName.OPERATION_INCOME_RATIO, ConfigOperationIncomeRatio.class);
        BigDecimal profit2platform2userf = configOperationIncomeRatio.getProfit2platform2user();
        //2.友豆兑换金额比例
        ConfigPaymentRateMoney2Coin configPaymentRateMoney2Coin = QuickHelper.getConfigValue(SystemConfigName.PAY_RATE_MONEY2COIN, ConfigPaymentRateMoney2Coin.class);
        BigDecimal payRateCoin2bean = new BigDecimal(QuickHelper.getConfigString(SystemConfigName.PAY_RATE_COIN2BEAN));
        BigDecimal globalRate = new BigDecimal(configPaymentRateMoney2Coin.getGlobalRate().toString()).multiply(payRateCoin2bean);
        //3.删除当天结算的全部数据，为了可以重新结算
        //当天
        Date date = new Date();
        //一天的开始，结果：2020-11-19 00:00:00
        Long beginOfDay = DateUtil.beginOfDay(date).getTime() / 1000;
        //一天的结束，结果：2020-11-19 23:59:59
        Long endOfDay = DateUtil.endOfDay(date).getTime() / 1000;
        //删除当天结算的记录
        userIncomeHistoryService.delete(new EntityWrapper<UserIncomeHistoryEntity>()
                .eq("type", "live").between("adddate", beginOfDay, endOfDay));
        guildIncomeHistoryService.delete(new EntityWrapper<GuildIncomeHistoryEntity>()
                .eq("type", "live").between("adddate", beginOfDay, endOfDay));
        platformIncomeDetailService.delete(new EntityWrapper<PlatformIncomeDetailEntity>()
                .eq("type", "live").between("adddate", beginOfDay, endOfDay));
        platformIncomeService.delete(new EntityWrapper<PlatformIncomeEntity>()
                .between("adddate", beginOfDay, endOfDay));

        //结算时间
        Integer settleTime = DateUtils.getSecondTimestamp(date);
        //统计平台收益
        BigDecimal platIncome = BigDecimal.ZERO;
        //4.联表查询出用户直播收入跟工会给主播设置分成比例
        List<SetteleLiveRewardsEntity> setteleLiveRewardsEntityList = liveRewardsService.selectLiveRewardsSetteleEntity();
        for (SetteleLiveRewardsEntity setteleLiveRewardsEntity : setteleLiveRewardsEntityList) {
            //友豆收入
            BigDecimal totalIncomeCoin = new BigDecimal(setteleLiveRewardsEntity.getTotalIncomeCoin().toString());
            //4.友豆转人民币收益
            BigDecimal totalInCome = totalIncomeCoin.divide(globalRate);
            Integer guildId = setteleLiveRewardsEntity.getGuildId();
            //会员收入
            BigDecimal memberIncome;
            //工会收入
            BigDecimal guildIncome = BigDecimal.ZERO;
            //平台收入
            BigDecimal platformIncome;
            //是否加入工会
            boolean isJoinGuild = null == guildId;
            //guildId为空，该用户无工会
            if (isJoinGuild) {
                //5.1无工会按平台与主播分成计算收益
                memberIncome = totalInCome.multiply(profit2platform2userf).setScale(2, BigDecimal.ROUND_HALF_UP);
                platformIncome = totalInCome.subtract(memberIncome);
            } else {
                //5.2有工会按工会给的提成比例计算，先计算主播，后计算工会，再计算平台
                memberIncome = totalInCome.multiply(setteleLiveRewardsEntity.getMemberProfitRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                //工会的提成=平台给工会的提成-工会给主播的提成
                guildIncome = totalInCome.multiply(setteleLiveRewardsEntity.getGuildProfitRate().subtract(setteleLiveRewardsEntity.getMemberProfitRate())).setScale(2, BigDecimal.ROUND_HALF_UP);
                //平台收入=总收入-工会收入-主播收入
                platformIncome = totalInCome.subtract(guildIncome).subtract(memberIncome);
            }

            //6.插入用户收益表
            UserIncomeHistoryEntity userIncomeHistoryEntity = new UserIncomeHistoryEntity();
            userIncomeHistoryEntity.setType("live");
            userIncomeHistoryEntity.setState(0);
            userIncomeHistoryEntity.setAdddate(settleTime);
            userIncomeHistoryEntity.setUid(setteleLiveRewardsEntity.getUid());
            userIncomeHistoryEntity.setIncomeMoney(memberIncome);

            if (userIncomeHistoryService.insert(userIncomeHistoryEntity)) {
                logger.info(String.format("插入用户收益表成功： %s", userIncomeHistoryEntity));
            }

            //7.插入工会收益表
            if (!isJoinGuild) {
                GuildIncomeHistoryEntity guildIncomeHistoryEntity = new GuildIncomeHistoryEntity();
                guildIncomeHistoryEntity.setGuildId(setteleLiveRewardsEntity.getGuildId());
                guildIncomeHistoryEntity.setFromUid(setteleLiveRewardsEntity.getUid());
                guildIncomeHistoryEntity.setIncomeMoney(guildIncome);
                guildIncomeHistoryEntity.setState(0);
                guildIncomeHistoryEntity.setType("live");
                guildIncomeHistoryEntity.setAdddate(settleTime);

                if (guildIncomeHistoryService.insert(guildIncomeHistoryEntity)) {
                    logger.info(String.format("插入工会收益表： %s", guildIncomeHistoryEntity));
                }
            }
            //8.插入平台收益表
            PlatformIncomeDetailEntity platformIncomeDetailEntity = new PlatformIncomeDetailEntity();
            platformIncomeDetailEntity.setAdddate(settleTime);
            platformIncomeDetailEntity.setFromUid(setteleLiveRewardsEntity.getUid());
            platformIncomeDetailEntity.setIncomeMoney(platformIncome);
            platformIncomeDetailEntity.setState(0);
            platformIncomeDetailEntity.setType("live");

            if (platformIncomeDetailService.insert(platformIncomeDetailEntity)) {
                logger.info(String.format("插入平台收益表： %s", platformIncomeDetailEntity));
            }

            //9.统计平台当天收益
            platIncome = platIncome.add(platformIncome);
        }
        //10.插入平台收益统计表
        PlatformIncomeEntity platformIncomeEntity = new PlatformIncomeEntity();
        platformIncomeEntity.setIncomeMoney(platIncome);
        platformIncomeEntity.setState(0);
        platformIncomeEntity.setAdddate(settleTime);
        platformIncomeService.insert(platformIncomeEntity);

        logger.info(String.format("任务完成 dailySettleAllAccountTask.run"));
    }


    public void test2() {
        logger.info("我是不带参数的test2方法，正在被执行");
    }
}
